using System;
using System.ComponentModel;
using System.Linq;
using System.Xml.Linq;
using Granite.Eventing;
using Granite.Modeling;
using Toon.Models.Catalogs;
using System.Collections.Specialized;

namespace Toon.Models.Characters
{
    public class Attribute : ChangeTrackingModelBase
	{
        readonly AttributeDefinition m_Definition;

        public Attribute(AttributeDefinition definition)
        {
            m_Definition = definition;
			Skills = new SkillCollection(from s in m_Definition.Skills select new Skill(this, s));
			Skills.CollectionChanged += Skills_CollectionChanged;
			Skills.ItemPropertyChanged += Skills_ItemPropertyChanged;

            PropertyChanged += (s, e) =>
            {
                foreach (var s2 in Skills)
                    s2.AttributePropertyChanged(e);
            };
        }

		public string Name
		{
			get { return m_Definition.AttributeName; }
		}

        public SkillCollection Skills
		{
			get { return Get<SkillCollection>("Skills"); }
			private set { Set(value, "Skills"); }
		}

		public int Value
		{
			get { return Get<int>("Value"); }
			set { Set(value, "Value"); }
		}

		public int SkillPointsSpent
		{
			get { return Skills.Sum(s => s.SkillPoints); }
		}

		void Skills_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			OnPropertyChanged("SkillPointsSpent");
		}

		void Skills_ItemPropertyChanged(object sender, RelayedEventArgs<PropertyChangedEventArgs> e)
		{
			OnPropertyChanged("SkillPointsSpent");
		}

        internal XElement ToXml()
        {
            return new XElement("Attribute",
                new XAttribute("Name", Name),
                new XAttribute("Value", Value),
                from s in Skills select new XElement(s.ToXml()));
        }



        internal void FromXml(XElement source)
        {
            Value = int.Parse(source.Attribute("Value").Value);
            foreach (var node in source.Elements("Skill"))
            {
                var skill = Skills[node.Attribute("Name").Value];
                skill.FromXml(node);
            }
        }

        public override string ToString()
        {
            return string.Format("{0} {1}", Name, Value);
        }
    }
}
